#region Copyright Notice
/*
Copyright (C) 2011 by Ashley Ross

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Copyright Notice

using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;

namespace Manta.IO {
    /// <summary>
    /// Provides methods for managing reparse points.
    /// </summary>
    public static class ReparsePoint
    {
        /// <summary>
        /// Gets the maximum size, in bytes, of the reparse point buffer.
        /// </summary>
        public const int MaximumReparsePointSize = 0x4000;


        /// <summary>
        /// Deletes a reparse point from the specified file or directory.
        /// </summary>
        /// <param name="item">The file or directory from which the reparse point is to be deleted.</param>
        /// <remarks>The reparse point associated with the file or directory is retrieved and then passed to the applicable overload of this method. This method does not delete the file or directory.</remarks>
        public static void Delete(FileSystemInfo item) {
            Write(item, Get<ReparseGuidDataBuffer>(item), IOControlCode.DeleteReparsePoint);
        }

        /// <summary>
        /// Deletes the specified reparse point from the specified file or directory.
        /// </summary>
        /// <param name="item">The file or directory from which the reparse point is to be deleted.</param>
        /// <param name="reparseData">The reparse point to delete. If the reparse point has them, the ReparseTag member must specify the tag of the reparse point to be deleted and the ReparseGuid member must specify the GUID of the reparse point to be deleted. The ReparseDataLength member must be zero.</param>
        /// <remarks>This method does not delete the file or directory.</remarks>
        public static void Delete(FileSystemInfo item, IReparseDataBuffer reparseData) {
            Write(item, reparseData, IOControlCode.DeleteReparsePoint);
        }

        /// <summary>
        /// Determines whether the specified file or directory exists and whether it contains a reparse point.
        /// </summary>
        /// <param name="item">The file or directory to check.</param>
        /// <returns>true if the file or directory exists and contains a reparse point; otherwise, false.</returns>
        public static bool Exists(FileSystemInfo item) {
            if (item == null)
                return false;

            item.Refresh();

            return item.Exists && ((item.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint);
        }

        /// <summary>
        /// Returns a new instance of the specified buffer type, populated with the data from the reparse point associated with the specified file or directory.
        /// </summary>
        /// <typeparam name="T">The buffer type to return. Must inherit from ReparseDataBufferBase and have a public parameterless constructor.</typeparam>
        /// <param name="item">The file or directory from which to retrieve the reparse point.</param>
        /// <returns>A new, populated instance of the specified buffer type.</returns>
        public static T Get<T>(FileSystemInfo item) where T : IReparseDataBuffer, new() {
            T reparseData = new T();
            Get(item, reparseData);
            return reparseData;
        }

        /// <summary>
        /// Populates the specified buffer with the data from the reparse point associated with the specified file or directory.
        /// </summary>
        /// <param name="item">The file or directory from which to retrieve the reparse point.</param>
        /// <param name="reparseData">The buffer to populate with the data retrieved from the file or directory.</param>
        public static void Get(FileSystemInfo item, IReparseDataBuffer reparseData) {
            IntPtr ioHandle;

            if (item == null)
                throw new ArgumentNullException("item");

            item.Refresh();

            if (!item.Exists)
                throw item is FileInfo ? (Exception) new FileNotFoundException() : (Exception) new DirectoryNotFoundException();

            if ((item.Attributes & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
                throw new InvalidOperationException();

            if (reparseData == null)
                throw new ArgumentNullException("reparseData");

            ioHandle = OpenFileSystemItem(item, AccessRights.GenericRead);

            try {
                IntPtr unmanagedBuffer = Marshal.AllocHGlobal(MaximumReparsePointSize);

                try {
                    uint bytesReturned = 0;

                    if (!NativeMethods.DeviceIoControl(ioHandle, IOControlCode.GetReparsePoint, IntPtr.Zero, 0, unmanagedBuffer, MaximumReparsePointSize, ref bytesReturned, IntPtr.Zero))
                        throw new Win32Exception(Marshal.GetLastWin32Error());

                    Marshal.PtrToStructure(unmanagedBuffer, reparseData);
                } finally {
                    Marshal.FreeHGlobal(unmanagedBuffer);
                }
            } finally {
                NativeMethods.CloseHandle(ioHandle);
            }
        }

        /// <summary>
        /// Sets the specified reparse point data on the specified file or directory.
        /// </summary>
        /// <param name="item">The file or directory on which to set the reparse point.</param>
        /// <param name="reparseData">The buffer containing the reparse point data.</param>
        public static void Set(FileSystemInfo item, IReparseDataBuffer reparseData) {
            Write(item, reparseData, IOControlCode.SetReparsePoint);
        }


        private static void Write(FileSystemInfo item, IReparseDataBuffer reparseData, IOControlCode operation) {
            IntPtr ioHandle;

            if (item == null)
                throw new ArgumentNullException("item");

            item.Refresh();

            if (!item.Exists)
                throw item is FileInfo ? (Exception) new FileNotFoundException() : (Exception) new DirectoryNotFoundException();

            if (reparseData == null)
                throw new ArgumentNullException("reparseData");

            ioHandle = OpenFileSystemItem(item, AccessRights.GenericWrite);

            try {
                IntPtr unmanagedBuffer = Marshal.AllocHGlobal(MaximumReparsePointSize);

                try {
                    uint bytesReturned = 0;

                    Marshal.StructureToPtr(reparseData, unmanagedBuffer, true);

                    if (!NativeMethods.DeviceIoControl(ioHandle, operation, unmanagedBuffer, reparseData.Size, IntPtr.Zero, 0, ref bytesReturned, IntPtr.Zero))
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                } finally {
                    Marshal.FreeHGlobal(unmanagedBuffer);
                }
            } finally {
                NativeMethods.CloseHandle(ioHandle);
            }
        }

        private static IntPtr OpenFileSystemItem(FileSystemInfo item, AccessRights rights) {
            IntPtr ioHandle = NativeMethods.CreateFile(item.FullName, rights, FileShare.None, IntPtr.Zero, CreationDisposition.OpenExisting, FileFlags.OpenReparsePoint | FileFlags.BackupSemantics, IntPtr.Zero);

            if (ioHandle.ToInt32() == -1)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            return ioHandle;
        }
    }
}